package com.cloudeasy.post.service.expand;

import com.cloudeasy.api.util.JsonUtil;
import com.cloudeasy.api.vo.post.PushVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class PushService {
    private static final String PERFIX = "push_%s";

    private final StringRedisTemplate redisTemplate;

    public PushService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 添加推送
     *
     * @param userId 用户Id
     * @param pushVO {@link PushVO}
     */
    public void push(String userId, PushVO pushVO) {
        if (pushVO != null) {
            redisTemplate.opsForList().leftPush(String.format(PERFIX, userId), JsonUtil.toJson(pushVO));
        }
    }

    /**
     * 获取推送
     *
     * @param userId 用户Id
     * @return {@link List<PushVO>}
     */
    public List<PushVO> get(String userId) {
        List<String> strings = redisTemplate.opsForList().range(String.format(PERFIX, userId), 0, -1);
        redisTemplate.expire(String.format(PERFIX, userId), 10, TimeUnit.MINUTES);
        return strings != null ? strings.stream().map(s -> JsonUtil.fromJson(s, PushVO.class)).collect(Collectors.toList()) : null;
    }
}
